package com.zhanglinwei.openApiServer.context;

import com.alibaba.fastjson2.JSON;
import com.zhanglinwei.common.utils.AssertUT;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

import static com.zhanglinwei.common.constants.StringPoolConstant.COLON;

@Slf4j
public class OpenApiContext {

    private static final Map<String, OpenApiMetadata> OPEN_API_CLASS_METHOD_MAPPING_MAP = new ConcurrentHashMap<>();

    public static Optional<OpenApiMetadata> get(String apiCode, String apiVersion) {
        return Optional.ofNullable(OPEN_API_CLASS_METHOD_MAPPING_MAP.get(openApiUniqueKey(apiCode, apiVersion)));
    }

    public static boolean containsKey(String key) {
        return OPEN_API_CLASS_METHOD_MAPPING_MAP.containsKey(key);
    }

    public static void registry(OpenApiMetadata openApiMetadata) {
        AssertUT.notNull(openApiMetadata, "openApiMetadata can not be null");
        String uniqueKey = openApiUniqueKey(openApiMetadata.getApiCode(), openApiMetadata.getApiVersion());
        AssertUT.isFalse(containsKey(uniqueKey), String.format("The %s already exists.", uniqueKey));

        OPEN_API_CLASS_METHOD_MAPPING_MAP.put(uniqueKey, openApiMetadata);
        log.info("## registry openApi success {}", JSON.toJSONString(openApiMetadata));
    }

    private static String openApiUniqueKey(String apiCode, String apiVersion) {
        return apiCode + COLON + apiVersion;
    }

    @Getter
    @Setter
    @Builder
    public static class OpenApiMetadata {
        private String apiCode;
        private String apiVersion;
        private String apiDescription;
        private String fullClassName;
        private String fullMethodName;
    }
}
